from quart import Quart, request, jsonify ,static_file

import aiohttp
import asyncio 

app = Quart(__name__)
app.add_url_rule('/static/<path:filename>', endpoint='static', view_func=static_file)

class User:
    def __init__(self,  token):
        self.token = token
        self.count = 0
        self.res = False

    def addCount(self):
        self.count+=1
    def get(self):
        return self.token


userList = []
def getUser(token):
    result1 = any(obj.get() == token for obj in userList)
    if result1 :
        for item in userList:
            if item.token == token:
                item.addCount()
                print(item.count)
                if item.count >= 3:
                    item.res=True
                    return True
    else:
        return False
#执行计算方法

asNum = 0
async def startCalc(params,token):
    global asNum
    asNum = 0
    ans = await addSleep()
    return ans

async def addSleep():
    global asNum
    await asyncio.sleep(1)
    if asNum>5:
        return "结果"
    else:
        asNum+=1
        return await addSleep()
    
async def fetch(session, url):
    async with session.get(url) as response:
        return await response.text()
    
async def calcImg(bodyMsg):
    async with aiohttp.ClientSession() as session:
        async with session.post('http://psdlink.dongtaiyuming.net/sdapi/v1/img2img', json=bodyMsg) as response:
            return await response.json()

@app.route('/sdapi/v1/img2img', methods=['POST'])
async def post_img():
    try:
        data = await request.get_json()
        # 获取token
        token = request.args['token']
        # 获取参数
        data = await request.get_json()
        user = User(token=token)
        userList.append(user)
        task1 = asyncio.create_task(calcImg(data))
        task2 = asyncio.create_task(startCalc(data,token))
        # Wait until both tasks are completed.
        result1 = await task1
        await task2
        if user.res:
            userList.remove(user)
            print('运算完成')
            return jsonify(result1), 200
        else:
            return jsonify({'error': '运算未完成提前！'}), 400
    except ValueError:
        return jsonify({'error': 'Not a valid JSON'}), 400

@app.route('/active', methods=['GET'])
async def get_active():
    try:
        token =  request.args.get("token", default=None, type=str)
        ans = getUser(token)
        if token:
            if ans :
                return jsonify({'message': '广告读取成功'}), 200
            else:
                return jsonify({'message': '广告读取失败'}), 200
        else:
            return jsonify({'error': 'Invalid JSON data. Missing fields.'}), 400
    except ValueError:
        return jsonify({'error': 'Not a valid JSON'}), 400

if __name__ == '__main__':
     app.run()